package net.wanho.study.util;

import net.wanho.study.test.Test01;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Author：汤小洋
 * Date：2023-06-30 13:39
 * Description：<描述>
 */
public class MyBatisUtil {
    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();

    static {
        try {
            // 创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            // 创建SqlSessionFactory对象
            factory = builder.build(Test01.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            throw new ExceptionInInitializerError("MyBatisUtil初始化失败："+e.getMessage());
        }
    }

    public static SqlSession getSession(){
        SqlSession session = local.get();
        if(session==null){
            session = factory.openSession();
            local.set(session);
        }
        return session;
    }

    public static void close(){
        SqlSession session = local.get();
        if(session!=null){
            session.close();
            local.remove();
        }
    }

    public static void main(String[] args) {
        System.out.println(getSession());
    }
}
